package com.stm.common.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class DoorUtils {

    //点击开门，传输信号给门禁
    public static void openDoor() {
        /*UDP 发送步骤
         *1. 建立DatagramSocket
         *2. 建立 DatagramPacket
         *3. 使用 DatagramSocket 的send 方法 发送数据
         *4. 关闭 DatagramSocket
         */
        //定义发送使用的端口，接收的IP地址
    	log.info("调用门禁openDoor（）方法");
        try {
            DatagramSocket ds = new DatagramSocket(10086);

            byte[] b = new byte[7];

            b[0] = (byte) 0XAA;
            b[1] = 1;
            b[2] = 3;
            b[3] = 1;
            b[4] = 5;
            b[6] = (byte) 0XBB;
            InetAddress ip = InetAddress.getByName("255.255.255.255");
        	log.info("门禁ip{}"+ip);
            DatagramPacket dp = new DatagramPacket(b, b.length, ip, 9999);
            ds.send(dp);
            ds.close();
            log.info("门禁消息发送成功！");
        } catch (SocketException e) {
//            e.printStackTrace();
            log.info("门禁消息发送失败！日志：{}"+e);
        } catch (IOException e) {
//            e.printStackTrace();
            log.info("门禁消息发送失败！日志：{}"+e);
        } catch (Exception e) {
        	log.info("门禁消息发送失败！日志：{}"+e);
        }


    }

    //人员改动，传输数据给门禁
    public static void peopleDoor() {

        for (int i = 0; i < 3; i++) {

            try {
                DatagramSocket ds = new DatagramSocket(10086);
                byte[] b = new byte[7];
                b[0] = (byte) 0XAA;
                b[1] = 2;
                b[2] = 3;
                b[3] = 2;
                b[6] = (byte) 0XBB;
                InetAddress ip = InetAddress.getByName("255.255.255.255");
                DatagramPacket dp = new DatagramPacket(b, b.length, ip, 9999);
                ds.send(dp);
                ds.close();
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


}
